import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getCategories, getCategoryById, createCategory, updateCategory, deleteCategory } from '@/api/category'

export const useCategoryStore = defineStore('category', () => {
  const categories = ref<any[]>([])
  const loading = ref<boolean>(false)
  const currentCategory = ref<any>(null)

  // 获取所有分类
  const fetchCategories = async () => {
    try {
      loading.value = true
      const response = await getCategories()
      if (response.data.success) {
        categories.value = response.data.categories
      }
      return response.data
    } catch (error: any) {
      console.error('获取分类失败:', error)
      return { success: false, message: error.response?.data?.message || '获取分类失败' }
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取分类
  const fetchCategoryById = async (id: number) => {
    try {
      loading.value = true
      const response = await getCategoryById(id)
      if (response.data.success) {
        currentCategory.value = response.data.category
      }
      return response.data
    } catch (error: any) {
      console.error('获取分类详情失败:', error)
      return { success: false, message: error.response?.data?.message || '获取分类详情失败' }
    } finally {
      loading.value = false
    }
  }

  // 创建分类
  const addCategory = async (categoryData: any) => {
    try {
      loading.value = true
      const response = await createCategory(categoryData)
      if (response.data.success) {
        // 重新获取分类列表
        await fetchCategories()
      }
      return response.data
    } catch (error: any) {
      console.error('创建分类失败:', error)
      return { success: false, message: error.response?.data?.message || '创建分类失败' }
    } finally {
      loading.value = false
    }
  }

  // 更新分类
  const editCategory = async (id: number, categoryData: any) => {
    try {
      loading.value = true
      const response = await updateCategory(id, categoryData)
      if (response.data.success) {
        // 重新获取分类列表
        await fetchCategories()
      }
      return response.data
    } catch (error: any) {
      console.error('更新分类失败:', error)
      return { success: false, message: error.response?.data?.message || '更新分类失败' }
    } finally {
      loading.value = false
    }
  }

  // 删除分类
  const removeCategory = async (id: number) => {
    try {
      loading.value = true
      const response = await deleteCategory(id)
      if (response.data.success) {
        // 重新获取分类列表
        await fetchCategories()
      }
      return response.data
    } catch (error: any) {
      console.error('删除分类失败:', error)
      return { success: false, message: error.response?.data?.message || '删除分类失败' }
    } finally {
      loading.value = false
    }
  }

  return {
    categories,
    loading,
    currentCategory,
    fetchCategories,
    fetchCategoryById,
    addCategory,
    editCategory,
    removeCategory
  }
}) 